package com.api.controller;

import com.api.utils.Time;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${root}")
    public String root;

    @Value("${ip}")
    public String IP;

    /**
     * 上传文件
     * @param file 文件
     * @param type 文件类型
     */
    @PostMapping("/up")
    public Map<String, Object> up(MultipartFile file, String type) throws IOException {
        Map<String, Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        if (file == null) {
            code = 500;
            msg = "文件不能为空";
        } else if (type == null) {
            code = 501;
            msg = "文件类型不能为空";
        } else {
            String fileName = "/" + Time.getStamp() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));     // 文件名：时间戳（毫秒）
            File dir = new File(root + type);
            if (!dir.exists()) dir.mkdirs();
            File fileObj = new File(dir + fileName);
            file.transferTo(fileObj);
            map.put("data", IP + type + fileName);
        }

        map.put("code",code);
        map.put("msg",msg);
        return map;
    }

    /**
     * 删除文件
     * @param url 文件 url
     */
    @DeleteMapping("/remove")
    public Map<String,Object> remove(String url) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        if (url == null) {
            code = 500;
            msg = "url 不能为空";
        } else {
            url = url.replaceAll(IP,root);;
            File file = new File(url);
            if (file.exists()) {
                if (!file.delete()) {
                    code = 502;
                    msg = "服务异常";
                }
            } else {
                code = 501;
                msg = "文件不存在";
            }
        }

        map.put("code",code);
        map.put("msg",msg);
        return map;
    }
}
